#include "console-common.h"
#include "lua-conwin.h"
#include "lua-fn-aliases.h"
#include <ctime>
#include <cstdlib>
#include <random> // must be added -std=gnu++11 option

static std::mt19937 __randgen (time(NULL));

static uint32_t __randint()
{
	return __randgen ();
}

static int __luacon_rndpos(lua_State *L)
{
	lua_pushinteger(L, __randint() % XCHRS);
	lua_pushinteger(L, __randint() % YCHRS);
	return 2;
}

static int __luacon_rndint(lua_State *L)
{
	int rands = lua_tointeger(L, 1);
	if (rands < 1) rands = 1;
	luaL_checkstack(L, rands, NULL);
	for (int i = 0; i < rands; i ++)
		lua_pushinteger(L, __randint());
	return rands;
}

static int __luacon_rndseed(lua_State *L)
{
	int seed = luaL_optinteger(L, 1, time(NULL));
	__randgen.seed(seed);
	return 0;
}

static int __luacon_rnddrawch(lua_State *L)
{
	size_t len;
	const char* str = luaL_checklstring(L, 1, &len);
	int p = luaL_optint_gfx_i(L, 2), x = __randint() % XCHRS, y = __randint() % YCHRS;
	drawchr(semigraphics_bufs[p], x, y, str[__randint() % len]);
	return 0;
}

void luarng_init_(lua_State *L)
{
	const static struct luaL_Reg lua_prng_api [] = {
		{"pos", __luacon_rndpos},
		{"int", __luacon_rndint},
		{"seed", __luacon_rndseed},
		{"draw_char", __luacon_rnddrawch},
		{"random", NULL},
		{NULL, NULL},
	};
	luaL_register_ext(L, lua_prng_api);
}
